import strSidebarHtml from "./Sidebar.html"; // 使用 raw-loader 加载 HTML 文件
import { DomUtils } from "../../utils/DomUtils"; // 引入 DomUtils 工具类

export class Sidebar {
  constructor(data) {
    // 如果没有传递数据，则使用默认数据
    this.data = data || {
      userName: "Sarah Smith",
      userRole: "Administrator",
      menuItems: [],
    };
  }

  render() {
    // 动态生成菜单项的 HTML
    const menuItemsHtml = this.generateMenuItemsHtml(this.data.menuItems);

    // 将数据模型动态替换到 HTML 模板中
    const sidebarHtml = strSidebarHtml
      .replace("{{userName}}", this.data.userName)
      .replace("{{userRole}}", this.data.userRole)
      .replace("{{menuItems}}", menuItemsHtml);

    // 调用 DomUtils 的静态方法将字符串转换为 DOM 元素
    return DomUtils.convertToDom(sidebarHtml);
  }

  generateMenuItemsHtml(menuItems) {
    return menuItems
      .map((item) => {
        if (item.type === "header") {
          return `<li class="menu-header">${item.title}</li>`;
        } else if (item.type === "dropdown") {
          const isActive = item.active ? "active" : "";
          const dropdownItemsHtml = this.generateDropdownItemsHtml(item.items);
          return `
            <li class="dropdown ${isActive}">
              <a href="#" class="nav-link has-dropdown">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="${item.icon}">
                  <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
                  <line x1="8" y1="21" x2="16" y2="21"></line>
                  <line x1="12" y1="17" x2="12" y2="21"></line>
                </svg>
                <span>${item.title}</span>
              </a>
              <ul class="dropdown-menu" style="display: none">
                ${dropdownItemsHtml}
              </ul>
            </li>
          `;
        }
        return "";
      })
      .join("");
  }

  generateDropdownItemsHtml(items) {
    return items
      .map((item) => {
        if (item.type === "dropdown") {
          const subDropdownItemsHtml = this.generateDropdownItemsHtml(
            item.items
          );
          return `
            <li class="dropdown">
              <a href="#" class="has-dropdown">${item.title}</a>
              <ul class="dropdown-menu">
                ${subDropdownItemsHtml}
              </ul>
            </li>
          `;
        } else {
          const isActive = item.active ? "active" : "";
          return `<li class="${isActive}"><a class="nav-link" href="${item.href}">${item.title}</a></li>`;
        }
      })
      .join("");
  }
}
